package com.jt;

import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;//注意是客户端的jedis
import org.springframework.boot.test.context.SpringBootTest;
import redis.clients.jedis.Transaction;

/*
  Jedis事务操作
 */
@SpringBootTest
public class JedisTransaction {

    @Test
    public  void  transaction(){
        Jedis jedis = new Jedis("192.168.126.128",6379);
        jedis.set("jack", "200");
        jedis.set("tony", "300");
        //实现操作,tony转账100给jack
        //1.开启事务
        Transaction multi = jedis.multi();
        //2.业务操作
        try {
            multi.decrBy("tony", 100);
            multi.incrBy("jack", 100);
            multi.exec();//3.提交事务
            //int n=100/0;//模拟异常JedisDataException: ERR DISCARD without MULTI
        }catch (Exception e){
            multi.discard();//4.取消事务
        }

        String tonyMoney = jedis.get("tony");
        String jackMoney = jedis.get("jack");

        System.out.println(tonyMoney);//200
        System.out.println(jackMoney);//300

        jedis.close();
    }

}
